package com.xjl.aI.mq.customer;

import com.xjl.aI.entity.AiMessageRes;
import com.xjl.aI.entity.DTO.DevicesCallBackMessageDTO;
import com.xjl.aI.service.AiMessageResService;
import com.xjl.tools.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.Date;

@Slf4j
@Service
@RocketMQMessageListener
        (topic = "${topic.ai.alarm}",
        consumerGroup = "AlarmGroup1",
        selectorExpression = "test",
        consumeMode = ConsumeMode.CONCURRENTLY, //消息类型,当前为并发消息,ORDERLY为顺序消息
        maxReconsumeTimes = 5)
public class AiAlarmTestCustomer implements RocketMQListener<DevicesCallBackMessageDTO> {


    String url ="http://192.168.137.156:8080/upload";
//    String url ="http://localhost:8080/upload";
    String pre = "D:\\Java_code_IDEA\\Test\\IOT-alarm\\iot-application\\app-starter\\src\\main\\resources\\static\\images\\";

    @Autowired
    AiMessageResService aiMessageResService;

    @Override
    public void onMessage(DevicesCallBackMessageDTO message) {
        log.info(message.toString());
        String picture = pre+message.getPicture();
        File file = new File(picture);
        if(file.exists()){
            String s = HttpUtils.executeFileImagePost(url, file);
            if(StringUtils.isNotBlank(s)){
                AiMessageRes aiMessageRes = AiMessageRes.builder()
                        .resPicturePath(s)
                        .messageId(message.getCallBackId())
                        .stationId(Integer.valueOf(message.getStationId()))
                        .deviceId(message.getDeviceId())
                        .createTime(new Date())
                        .build();
                aiMessageResService.save(aiMessageRes);
            }
        }else{
            log.error(" 图片文件不存在!! ");
        }
    }
}
